<template>
  <view>
	  <!-- 公共组件-每个页面必须引入 -->
	  <public-module></public-module>
    <view class="dialog-quotation">
		<div style="background: #fff;padding:0 32rpx">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="form" labelWidth="100" errorType="toast">
				<u-form-item  label=" " prop="purchasePrice" borderBottom labelWidth="0">
					<div style="display: flex;justify-content: space-between;align-items: center;height:80rpx;">
						<div style="font-weight: bold;width:100rpx;font-size:36rpx;">价格</div>
						<u--input @focus="upInfo('我要报价弹出页面&价格&',form.purchasePrice)" :customStyle="{'font-weight':'bold'}" fontSize="18" inputAlign="right" v-model="form.purchasePrice" border="none"  placeholder="请输入价格" type="number"></u--input>
					</div>
				</u-form-item>
				<u-form-item  :label="servicePs" borderBottom labelWidth="250">
					<div style="text-align: right;">{{serviceChargeRatio | fifterNum(form.priceNum,form.purchasePrice,serviceType)}}元/吨</div>
				</u-form-item>
				<u-form-item  label="合计报价" borderBottom >
					<div style="text-align: right;color:red;font-weight: bold;">{{serviceChargeRatio | fifterNum2(form.priceNum,form.purchasePrice,serviceType)}}元/吨</div>
				</u-form-item>
				<u-form-item label="公司抬头"  borderBottom @click="showChooseDP" prop="storeName">
					<u--input fontSize="14" inputAlign="right" :value="form.storeName" disabled disabledColor="none" placeholder="请选择公司抬头" border="none" style="pointer-events: none"></u--input>
					<div slot="right" class="form-icon">
						<u-icon slot="right" name="arrow-right" ></u-icon>
					</div>
				</u-form-item>
				<u-form-item  label="数量(吨)" prop="priceNum" borderBottom>
					<u--input  fontSize="14" @focus="upInfo('我要报价弹出页面&数量&',form.priceNum)" inputAlign="right" v-model="form.priceNum" border="none"  placeholder="请输入数量"></u--input>
				</u-form-item>
				
				<u-form-item  label="仓库地址" borderBottom prop="sendArea">
					<uni-data-picker v-slot:default placeholder="请选择仓库地址" popup-title="请选择仓库地址" :localdata="dataTree"
					  :modelValue="areaId"
					  :map="{text:'areaName',value:'areaId'}" @change="onchange" @popupopened="onpopupopened"
					  @popupclosed="onpopupclosed" :clear-icon="false" style="width:100%">
					  <view class="form-row ">
					    <view class="input" style="display: block;" v-if="form.sendArea != ''"> {{form.sendArea}}</view>
					    <view v-else><text style="color:#c0c4cc">请选择仓库地址</text></view>
					    <u-icon slot="right" name="arrow-right" ></u-icon>
					  </view>
					</uni-data-picker>
				</u-form-item>
				<u-form-item label="发货时间"  borderBottom @click="showDate('sendDate')" prop="sendDate">
					<u--input fontSize="14" inputAlign="right" :value="form.sendDate" disabled disabledColor="none" placeholder="请选择发货时间" border="none" style="pointer-events: none"></u--input>
					<div slot="right" class="form-icon">
						<u-icon slot="right" name="arrow-right" ></u-icon>
					</div>
				</u-form-item>
				<u-form-item  label="配送方式"  borderBottom>
					<div style="text-align: right;">{{form.priceSendTypes}}</div>
					<!-- <u-radio-group  v-model="form.priceSendTypes" placement="row" :customStyle="{justifyContent:'flex-end'}" @change="upInfo('我要报价弹出页面&配送方式点选',form.priceSendTypes)">
						<u-radio label="自提" :customStyle="{marginRight: '16px'}" name="自提"></u-radio>
						<u-radio label="送到" name="送到"></u-radio>
					</u-radio-group> -->
				</u-form-item>
				<u-form-item  label="结算方式"  borderBottom>
					<div style="text-align: right;">{{form.pricePayTypes}}</div>
					<!-- <u-radio-group  v-model="form.pricePayTypes" placement="row" :customStyle="{justifyContent:'flex-end'}" @change="upInfo('我要报价弹出页面&结算方式点选',form.pricePayTypes)">
						<u-radio label="现汇" :customStyle="{marginRight: '16px'}" name="现汇"></u-radio>
						<u-radio label="承兑" name="承兑"></u-radio>
					</u-radio-group> -->
				</u-form-item>
				<u-form-item  label="报价有效期" borderBottom prop="validEndTime">
					<div class="form-row">
						<u--input fontSize="14" inputAlign="right" type="number" v-model="form.validEndTime"  placeholder="请输入" :customStyle="{'width':'150rpx',flex: 'none','marginRight': '10px','height': '35px','border':'solid 1px #e5e5e5 !important' }"></u--input>
						<uni-data-select v-model="form.validEndTimeType" :localdata="range" @change="change" label="" :clear="false" style="width:150rpx"></uni-data-select>
					</div>	
				</u-form-item>	
				<div v-for="item in formKey" :key="item.key">
					<u-form-item :label="item.name"  borderBottom  @click="showList(item)" :prop="item.key" v-if="item.type == 'radio'">
						<u--input fontSize="14" inputAlign="right" :value="form[item.key]" disabled disabledColor="none" :placeholder="'请选择'+item.name" border="none" style="pointer-events: none"></u--input>
						<div slot="right" class="form-icon">
							<u-icon slot="right" name="arrow-right" ></u-icon>
						</div>
					</u-form-item>
					<u-form-item :label="item.name"  borderBottom   :prop="item.key" v-else-if="item.type == 'input'">
						<u--input  fontSize="14" inputAlign="right" v-model="form[item.key]" border="none"  :placeholder="'请输入'+item.name"></u--input>
					</u-form-item>
				</div>
				<u-form-item  label="产品说明" borderBottom >
					<u--input  fontSize="14" inputAlign="right" v-model="form.priceRemark" border="none"  placeholder="请输入产品说明"></u--input>
				</u-form-item>	
				
			</u--form>
		</div>
      
    </view>
	<view class="change-button" style="z-index: 3;">
	  <u-button :text="!includeProduct ? '您经营的产品线不适合此次报价' : '提交报价'" color="linear-gradient(180deg, #FF5E01 0%, #FF5E01 100%)"  @click="saveForm" :loading="btnLoading" :disabled="!includeProduct"></u-button> <!--:disabled="!includeProduct"-->
	</view>
    <!--时间选择-->
     <u-datetime-picker :show="showTime" v-model="value1"  :mode="mode1" @confirm="confirmTime" @cancel="showTime=false"></u-datetime-picker>
     <!--颜色-->
     <chooseList ref="chooseList" @chooseItem="chooseList"></chooseList>
	 
	 <storeChoose ref="storeChoose" @chooseItem="changeStore"></storeChoose>
  </view>
</template>

<script>
	const defaultForm={
	  	    priceNum:'',
			purchasePrice:'',
			sendDate:'',
			sendArea:'',
			priceSendTypes:'',
			pricePayTypes:'',
			inquiryId:'',
			validEndTime:1,
			validEndTimeType:'day',
			storeName:'',
			priceStoreId:''
	      };
 import {getAreaList,editPrice,getSpecList,userSellerStore,checkPriceGoodsCate} from '@/config/api.js'
 import {priceDetail} from '@/config/api2.js'
 import chooseList from '@/components/module/chooseList'
 import storeChoose from '@/components/module/storeChoose';
 import store from '@/store';
 const log = require('@/plugins/log.js')
  export default {
	  components: {
	    chooseList,storeChoose
	  },
    data() {
    	return {
           show:false,
    	   form:JSON.parse(JSON.stringify(defaultForm)),
    	   btnLoading:false,
    	   key:'',
    	   dataTree: [],
    	   showTime:false,
    	   value1: '',
    	   mode1:'',
    	   title:'我要报价',
    	   type:'',
    	   rules:{
    	   	priceNum: [{
    	   			required: true,
    	   			message: '请输入数量',
    	   			// 可以单个或者同时写两个触发验证方式
    	   			trigger: ['blur', 'change']
    	   		}],
    	   	purchasePrice: [
				{
					required: true,
					type: 'number',
					message: '价格请输入非负数',
					// 可以单个或者同时写两个触发验证方式
					trigger: ['blur', 'change']
				},
				{
				// 自定义验证函数，见上说明
				validator: (rule, value, callback) => {
					// 上面有说，返回true表示校验通过，返回false表示不通过
					// uni.$u.test.mobile()就是返回true或者false的
					return value > 0
				},
				message: '价格请输入非负数',
				// 触发器可以同时用blur和change
				trigger: ['change','blur'],
			}

			],
    		sendDate: [{
    				required: true,
    				message: '请选择发货时间',
    				// 可以单个或者同时写两个触发验证方式
    				trigger: ['change']
    			}],
    		sendArea: [{
    				required: true,
    				message: '请选择仓库地址',
    				// 可以单个或者同时写两个触发验证方式
    				trigger: [ 'change']
    			}],
    		priceSendTypes: [{
    				required: true,
    				message: '请选择配送方式',
    				// 可以单个或者同时写两个触发验证方式
    				trigger: ['change']
    			}],
    		pricePayTypes: [{
    				required: true,
    				message: '请选择结算方式',
    				// 可以单个或者同时写两个触发验证方式
    				trigger: ['change']
    			}],
    		validEndTime: [{
    				required: true,
    				message: '请输入报价有效期',
    				type:'number',
    				// 可以单个或者同时写两个触发验证方式
    				trigger: ['blur', 'change']
    			}],
			storeName:[{
				required: true,
				message: '请选择公司抬头',
				// 可以单个或者同时写两个触发验证方式
				trigger: ['change']
			}],
    	   },
    	   areaId:'',
    	   range:[
    			{ value: 'day', text: "天" },
    			{ value: 'hour', text: "小时" },
    		  ],
    	  serviceChargeRatio:'',
    	  formKey:[],
		  priceId:'',
		  serviceType:'',
		  servicePs:'',
		  includeProduct:false
		 
    	  
    	}
    },
    onLoad(e) {
		console.log("e",e)
		this.form = JSON.parse(JSON.stringify(defaultForm));
		
	  this.type = e.type;
	  this.areaId = ''
	  this.priceId = e.priceId ? e.priceId : '';
	 
	  if(this.type == 'add'){
		  this.form.inquiryId = e.inquiryId
		  this.form.priceNum = e.priceNum;
		  this.form.priceSendTypes = e.sendTypes;
		  this.form.pricePayTypes = e.payTypes;
	      this.serviceChargeRatio = e.serviceChargeRatio;
		  this.serviceType = e.serviceType;
		  
		  if(this.serviceType == 0){
			 this.servicePs =  '成交后佣金（'+this.serviceChargeRatio+'元/公斤)'
		  }else{
			  this.servicePs =  '成交后佣金（'+parseFloat(this.serviceChargeRatio) * 100 +'%)'
		  }
	  }
	  this.init()
	  // #ifdef MP
	  this.$refs.form.setRules(this.rules)
	  // #endif
    },
    
    filters:{
    	fifterNum(val,priceNum,price,type){
			if(type == 0){
				if(parseFloat(val)*1000){
					return (parseFloat(val)*1*1000).toFixed(2)
				}else{
					return 0.00
				}
			}else if(type == 1){
				if(parseFloat(val)*1*parseFloat(price)){
					return (parseFloat(val)*1*parseFloat(price)).toFixed(2)
				}else{
					return 0.00
				}
			}	
    	},
		fifterNum2(val,priceNum,price,type){
			let price2 = 0
			if(type == 0){
				if(parseFloat(val)*1000){
					price2 =  (parseFloat(val)*1*1000).toFixed(2)
				}else{
					price2 =  0.00
				}
			}else if(type == 1){
				if(parseFloat(val)*1*parseFloat(price)){
					price2 =  (parseFloat(val)*1*parseFloat(price)).toFixed(2)
				}else{
					price2 =  0.00
				}
			}
				
			return parseFloat(price) + parseFloat(price2) ? (parseFloat(price) + parseFloat(price2)).toFixed(2) : 0.00
			
		},
    },
    methods: {
		upInfo(title,val){
			log.info(title+val);
		},
		//切换店铺
		changeStore(item){
			this.form.priceStoreId = item.storeId;
			this.form.storeName = item.storeName;
			this.getIncludeProduct();
		},
		//获取是否经营该产品
		getIncludeProduct(){
			checkPriceGoodsCate({priceStoreId:this.form.priceStoreId,inquiryId:this.form.inquiryId}).then((res)=>{
				this.includeProduct = res
			}).catch(()=>{
				this.includeProduct = false
			})
		},
		
		//显示店铺选择
		showChooseDP(){
			this.$refs.storeChoose.init(this.form.priceStoreId);
		},
		
    	showList(item){
    		this.$refs.chooseList.init(this.form[item.key],item);
    	},
    	chooseList(key,e){
    		this.form[key] = e;
    	},
    	init(){
    		if(this.type == 'add'){
    			this.title = '我要报价'
				getSpecList({inquiryId:this.form.inquiryId}).then((res2)=>{
					this.formKey = res2;
					this.formKey.forEach((el)=>{
						this.$set(this.form,el.key,'')
					})
				})
				this.form.priceStoreId = store.state.userInfo.storeId
				this.form.storeName = store.state.userInfo.storeName
				this.getIncludeProduct();
    		}else{
    			this.priceDetailInfo()
    			this.title = '修改报价'
    		}
			uni.setNavigationBarTitle({
				title: this.title
			});
    		this.getDataList()
    		this.show = true;	
    		
    	},
    	priceDetailInfo() {
    	  priceDetail({priceId:this.priceId}).then(res => {
		    this.serviceChargeRatio = res.perServiceCharge;
    	    this.form.purchasePrice = res.originalPurchasePrice
    	    this.form.priceNum = res.priceNum
    	    this.form.sendArea = res.sendArea
    	    this.form.sendDate = res.sendDate
    	    this.form.sendDates = res.sendDate
    	    this.form.priceSendTypes = res.priceSendTypes
    	    this.form.pricePayTypes = res.pricePayTypes
    	    this.form.priceId = res.priceId
    		this.form.validEndTime = res.validEndTimeType == 'day' ? res.validEndTimeByDay : res.validEndTimeByHour
    		this.form.validEndTimeType = res.validEndTimeType;
			this.form.priceRemark = res.priceRemark;
			this.serviceType = res.serviceType;
			this.form.priceStoreId = res.priceStoreId;
			this.form.storeName = res.storeName;
			this.form.inquiryId = res.inquiryId
			this.areaId = res.sendAreaId
			if(this.serviceType == 0){
			   this.servicePs =  '成交后佣金（'+this.serviceChargeRatio+'元/公斤)'
			}else{
			   this.servicePs =  '成交后佣金（'+this.serviceChargeRatio * 100 +'%)'
			}
			getSpecList({inquiryId:res.inquiryId}).then((res2)=>{
				this.formKey = res2;
				this.formKey.forEach((el)=>{
					this.$set(this.form,el.key,res[el.key])
				})
			})
			this.getIncludeProduct();
    		
    	  })
    	},
		
    	//显示时间选择
    	showDate(key){
    		this.key = key;
    		this.mode1 = key == 'sendDate' ? 'date' : 'datetime';
    		let date = this.form[this.key] ? new Date(this.form[this.key]) :new Date()
    		this.value1 = Number(date);
    		this.showTime = true;
			let text =  key == 'sendDate' ? '我要报价弹出页面&发货时间选择按钮' : '';
			if(text != ''){
			log.info(text)	
			}
			
    	},
    	confirmTime(e){
    		this.form[this.key] = this.result(e.value, e.mode);
    		this.showTime = false;
    	},
    	result(time, mode) {
    		const timeFormat = uni.$u.timeFormat;	
    		switch (mode) {
    			case 'datetime':
    				return timeFormat(time, 'yyyy-mm-dd hh:MM')
    			case 'date':
    				return timeFormat(time, 'yyyy-mm-dd')
    			
    		}
    	},
    	getDataList() {
    	  getAreaList().then((res) => {
    	    this.dataTree = res;
    	  })
    	},
    	onpopupopened() {
    	  console.log('popupopened');
		  let text = '我要报价弹出页面&厂库地区选择按钮';
		  log.info(text)
    	},
    	onpopupclosed() {
    	  console.log('popupclosed');
    	},
    	onchange(e) {
    	  let ids = [];
    	  let txts = [];
    	  e.detail.value.forEach((item) => {
    	   txts.push(item.text)
    	   ids.push(item.value)
    	  });
    	  this.areaId = ids[2] ? ids[2] : '' 
    	  this.form.sendArea = txts.join(" ")
		  log.info('我要报价弹出页面&厂库地区弹窗&'+this.form.sendArea)
    	},
    	saveForm(){
    		this.$refs.form.validate().then(res => {
    			let reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
    			let reg2 = /^[1-9]\d*$/;
    			if(!reg.test(this.form.priceNum) && this.form.priceNum !== ''){
    				uni.showToast({
    				  title: '输入数据不合法，请输入正数',
    				  duration: 1000,
    				  icon: 'none'
    				})
    				return false
    			}
    			if(!reg2.test(this.form.validEndTime) && this.form.validEndTime !== ''){
    				uni.showToast({
    				  title: '输入数据不合法，请输入正整数',
    				  duration: 1000,
    				  icon: 'none'
    				})
    				return false
    			}
    		   this.btnLoading = true;
    		   let  data = JSON.parse(JSON.stringify(this.form));
    		   if(this.type == 'edit'){
    			   delete data.inquiryId  
    		   }
			       data.sendAreaId = this.areaId
				   console.log(data)
    			 editPrice(data).then((res)=>{
    				   this.btnLoading = false;
					   
    				   // this.closeShow();
    				   uni.showToast({
    				     title: '已成功报价！请注意客户查看情况！',
    				     icon: 'none',
    				     duration: 2000,
    				   });
					   setTimeout(()=>{
						   uni.navigateBack();
					   },1000)
					   
					   let text = '我要报价弹出页面&发布报价按钮&'+ JSON.stringify(data)
					   log.info(text)
					   // #ifdef MP-WEIXIN
    				   wx.requestSubscribeMessage({
    				     tmplIds: ['O_O9OKETMf5A6Q-z8MfyrZutlrUCYCBtWRKjYzPeuvg','R7bgDnCd2c3RcHZvAGVNWmJgmI-AxwL-aUqcGsIpkL4','taD593KxeXZ2t65spUHzuk1HoSY2xDf7989BkafU7DA'],
    				     success (res) {
    				   			
    				   		},
    				   		fail(res){
    				   			// console.log("res",res)
    				   		},
    				   		complete(){
    				   			// console.log("89646456")
    				   		}
    				   })  
						// #endif
    				   // this.$emit('refresh')
    			 }).catch(()=>{
    				   this.btnLoading = false;
    			 })
    		}).catch(errors => {
    			
    		})
    		
    	},
       closeShow(){
    	   this.show = false
       }
   }
}
</script>

<style lang="scss" scoped>
  @import '@/style/common.scss';

  .dialog-quotation {
	padding-bottom:200rpx;

    .dialog-title {
      padding: 20rpx 10rpx;
      margin-bottom: 2px;
      font-size: $m-font;
      border-bottom: 0.8px solid $border-color;
      background-color: rgba(242, 242, 242, 1);
    }

  }
  .change-button {
    width: 100%;
    position: fixed;
    background-color: #fff;
    padding: 20rpx;
    bottom: 0;
    display: inline-block;
	z-index: 1;
  }

  .form-row {
    @include flexbox(flex-end, center);
  }
</style>